import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ClassFileEncrypt {
    static List<String> classFiles = new ArrayList<String>();


    static List<String> filterClassFile(String directory) {
        File filedirectory = new File(directory);
        if (filedirectory.exists() && filedirectory.isDirectory()) {
            String[] subdirectory = filedirectory.list();
            for (String sub : subdirectory) {
                sub = directory + "/" + sub;
//                System.out.println( sub);
                File subfile = new File(sub);
                if (subfile.isDirectory()) {
                    filterClassFile(sub);
                } else if (subfile.isFile() && sub.endsWith(".class")) {
                    classFiles.add(sub);
                }
            }
        } else {
            classFiles = null;
        }
        return classFiles;
    }

    static void encryptClassFile(String classfile, String directory) {
        try {
            FileInputStream fileInputStream = new FileInputStream(classfile);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 100];
            int len = 0;
            while ((len = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            String encrypted = AESUtil.encrypt(new String(outputStream.toByteArray()), "1234");
            System.out.println(encrypted);
            fileInputStream.close();
            outputStream.close();
            int offset = directory.length();
            System.out.println(offset);
            String encryptedFileName = directory + "/encrypt" + classfile.substring(offset);
            String encryptedDirectory = encryptedFileName.substring(0,encryptedFileName.lastIndexOf("/"));
            new File(encryptedDirectory).mkdirs();
            System.out.println(encryptedFileName);
            File encryptedFile = new File(encryptedFileName);
            if (encryptedFile.createNewFile() == true) {
                FileOutputStream fileOutputStream = new FileOutputStream(encryptedFile);
                fileOutputStream.write(encrypted.getBytes("utf-8"));
                fileOutputStream.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static void main(String[] args) {
        String directory = "/root/IdeaProjects/servletdemo/target";
        classFiles = filterClassFile(directory);
        System.out.println(classFiles.size());
        for (String classfile : classFiles) {
            encryptClassFile(classfile, directory);
        }
    }
}
